package code.hkgolden.android.activity;

import java.util.Collection;
import java.util.concurrent.Callable;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import code.framework.android.activity.ActivityConfigurator;
import code.framework.android.view.ListAdapterBase;
import code.hkgolden.android.core.HkgoldenContext;
import code.hkgolden.android.core.HkgoldenListActivityBase;
import code.hkgolden.android.core.HkgoldenTaskManager;
import code.hkgolden.android.data.Channel;
import code.hkgolden.android.data.Topic;
import code.hkgolden.android.service.ContentService;
import code.hkgolden.android.view.NavBarViewHolder;
import code.hkgolden.android.view.TopicViewHolder;

import com.google.inject.Inject;

public class TopicListActivity extends HkgoldenListActivityBase {

	public class TopicListAdapter extends ListAdapterBase<Topic> {
		public TopicListAdapter(Context c) {
			super(c);
		}

		@Override
		public long getItemId(int position) {
			final Topic topic = (Topic) super.getItem(position);
			return topic.getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TopicViewHolder topicViewHolder = null;
			if (convertView == null) {
				topicViewHolder = TopicListActivity.super.hkgoldenViewManager
						.createTopicBriefViewHolder(parent,
								TopicListActivity.this);
				convertView = topicViewHolder.container;
				convertView.setTag(topicViewHolder);
			} else {
				topicViewHolder = (TopicViewHolder) convertView.getTag();
			}
			final Topic topic = ts.get(position);
			TopicListActivity.super.hkgoldenViewManager.renderTopicViewHolder(
					topic, topicViewHolder);
			return convertView;
		}
	}

	private class ContentLoader implements Callable<Object> {
		@Override
		public Object call() throws Exception {
			logger.debug("call()");
			try {
				progressHandler.notify(HkgoldenTaskManager.REQUEST);
				final Collection<Topic> topics = contentService.topics(
						TopicListActivity.this.channel.getKey(), 0,
						TopicListActivity.super.hkgoldenContext
								.getApplicationPreference().getPageSize());
				progressHandler.notify(HkgoldenTaskManager.LOAD);
				if (topics != null && topics.size() > 0) {
					progressHandler.sendSerializableCollection(topics,
							contentHandler);
				}
			} catch (Exception e) {
				logger.error("uncaughtException", e);
			}
			return null;
		}
	}

	private class ContentHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			logger.debug("handleMessage()");
			final Bundle b = msg.getData();
			final Topic t = (Topic) b.getSerializable(Topic.class
					.getSimpleName());
			topicListAdapter.add(t);
			progressHandler.notify(HkgoldenTaskManager.RENDER);
		}
	}

	static final int PAGE_REQUEST_CODE = 0;

	Channel channel;
	int id;
	int page;

	TopicListAdapter topicListAdapter;

	ContentLoader contentLoader = new ContentLoader();

	ContentHandler contentHandler = new ContentHandler();

	HkgoldenTaskManager.ProgressHandler progressHandler;

	@Inject
	ContentService contentService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		logger.debug("onCreate()");
		super.onCreate(savedInstanceState);

		channel = super.hkgoldenContext.getRequestChannel(this);
		page = 1;

		final NavBarViewHolder navBarViewHolder = super.hkgoldenViewManager
				.createNavBarViewHolder(this, channel.getValue());
		progressHandler = super.hkgoldenViewManager.createProgressHandler(this);
		topicListAdapter = new TopicListAdapter(this);
		super.getListView().setAdapter(topicListAdapter);

		load();
	}

	@Override
	protected void load() {
		logger.debug("load()");
		topicListAdapter.clear();
		super.setProgress(0);
		ActivityConfigurator.setupDeterminateProcess(this);
		super.hkgoldenApplication.submit(contentLoader);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		logger.debug("onListItemClick() position = {}, id = {}", position, id);

		this.id = (int) id;
		final Topic topic = (Topic) topicListAdapter.getItem(position);
		if (topic.getRepliesCount() <= 30) {
			super.hkgoldenContext.requestReplies(this.id, 1, this);
		} else {
			int maxPage = topic.getRepliesCount() / 30 + 1;
			final Intent intent = new Intent(this, SelectActivity.class);
			intent.putExtra(HkgoldenContext.KEY_MAX_PAGE, maxPage);
			this.startActivityForResult(intent, PAGE_REQUEST_CODE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		logger.debug("onActivityResult() requestCode = {}, resultCode = {}",
				requestCode, resultCode);
		switch (requestCode) {
		case (PAGE_REQUEST_CODE): {
			if (resultCode == Activity.RESULT_OK) {
				this.page = intent.getIntExtra(HkgoldenContext.KEY_PAGE, 0);
				logger.trace("page = {}", page);
				super.hkgoldenContext.requestReplies(this.id, page, this);
			}
			break;
		}
		}
	}

}
